package com.globalblue;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.SwingWorker;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.globalblue.view.ImprovedMainWindow;

public class BackupThreadHandler extends SwingWorker<Boolean, Integer> {
	public static final String BASE_FOLDER = "C:/Delivery";
	private final Logger logger = Logger.getLogger(BackupThreadHandler.class);
	private String ticketId;
	ImprovedMainWindow window;
	private String username;
	private String password;

	public BackupThreadHandler(String ticketId, ImprovedMainWindow window,
			String username, String password) {
		this.ticketId = ticketId;
		this.window = window;
		this.username = username;
		this.password = password;
	}

	@Override
	protected Boolean doInBackground() {
		BackupManager bm = new BackupManager();
		DateFormat df = new SimpleDateFormat("ddMMyyyy HHmmss");
		Date currentTime = Calendar.getInstance().getTime();
		Calendar now = Calendar.getInstance();
		final int year = now.get(Calendar.YEAR);
		final String month = new SimpleDateFormat("MMM").format(now.getTime());

		try {
			String websiteFolderUpdated = Configurations.getWebsiteDirectory()
					.replace("\\", "/");
			String[] sourceSplit = websiteFolderUpdated.split("/");
			String backupFileName = sourceSplit[sourceSplit.length - 1] + "_"
					+ df.format(currentTime) + ".zip";
			String destination = BASE_FOLDER + "/" + year + "/" + month + "/"
					+ ticketId;
			bm.zipFolder(websiteFolderUpdated, destination + "/"
					+ backupFileName);
			logger.log(Level.INFO, "Finish Backuping existing web folder");
		} catch (Exception backupEx) {
			ErrorHandler.showErrorMessage(window,
					"Error occured while backingup files. Please try again");
		}

		String zipDestination = BASE_FOLDER + "/" + year + "/" + month + "/"
				+ ticketId;
		String[] buildPathSplit = Configurations.getBuildUrl().split("/");
		String buildFileName = buildPathSplit[buildPathSplit.length - 1];

		Configurations.setZipFileLocation(zipDestination + "/" + buildFileName);
		Configurations.setExtractedLocation(zipDestination + "/"
				+ buildFileName.replace(".zip", ""));
		File downloadFile = new File(Configurations.getZipFileLocation());
		if (downloadFile.exists()) {
			System.out.println("File already exists");
			logger.log(Level.INFO, "Extracting Files");
			try {
				window.changeStatus("images\\backup in progress.gif",
						"Extracting files...");
				FileUnzip unzip = new FileUnzip();
				unzip.ExtractAllFiles(Configurations.getZipFileLocation(),
						Configurations.getExtractedLocation());
				logger.log(Level.INFO, "Finished Extracting Files");
			} catch (Exception extractEx) {
				ErrorHandler.showErrorMessage(window,
						"Error extracting build file. Please try again");
			}

			FileListDisplay display = new FileListDisplay();
			List<String> fileList = display.getFileList(Configurations
					.getExtractedLocation());
			window.showFileListWindow(fileList);

		} else {
			logger.log(Level.INFO, "Downloading build file");

			String authString = username + ":" + password;
			System.out.println("auth string: " + authString);
			byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
			String authStringEnc = new String(authEncBytes);
			System.out.println("Base64 encoded auth string: " + authStringEnc);

			try {
				URL url = new URL(Configurations.getBuildUrl());
				URLConnection urlConnection = url.openConnection();
				HttpURLConnection huc = ((HttpURLConnection) urlConnection);
				huc.setRequestMethod("HEAD");
				huc.connect();

				int respCode = huc.getResponseCode();
				if (respCode != 100) {
					ErrorHandler
							.showErrorMessage(window,
									"Could not download build file. Please check the details and try again");
				} else {
					urlConnection.setRequestProperty("Authorization", "Basic "
							+ authStringEnc);
					respCode = ((HttpURLConnection) urlConnection)
							.getResponseCode();

					ProgressBarDisplay progressBar = new ProgressBarDisplay(
							urlConnection.getContentLengthLong(), window);
					progressBar.execute();

					FileDownloader fd = new FileDownloader();

					fd.downloadFile(urlConnection,
							Configurations.getZipFileLocation(), window);

					logger.log(Level.INFO, "Finish Downloading build file");

					logger.log(Level.INFO, "Extracting Files");
					try {
						window.changeStatus("images\\backup in progress.gif",
								"Extracting files...");
						FileUnzip unzip = new FileUnzip();
						unzip.ExtractAllFiles(
								Configurations.getZipFileLocation(),
								Configurations.getExtractedLocation());
						logger.log(Level.INFO, "Finished Extracting Files");
					} catch (Exception extractEx) {
						ErrorHandler.showErrorMessage(window,
								"Error extracting build file. Please try again");
					}

					FileListDisplay display = new FileListDisplay();
					List<String> fileList = display.getFileList(Configurations
							.getExtractedLocation());
					window.showFileListWindow(fileList);
				}
			} catch (Exception e) {
				ErrorHandler
						.showErrorMessage(window,
								"Could not download build file. Please check the details and try again");
			}
		}

		return true;
	}

	public void showDialog() {
	}

}
